package com.you.common.ibatis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.you.common.ibatis.data.DataList;
import com.you.common.ibatis.param.QueryParam;

@SuppressWarnings("unchecked")
public class SqlMapClientTemplate extends org.springframework.orm.ibatis.SqlMapClientTemplate {

    public DataList pagedQuery(QueryParam queryParam, final String statementName) {

        String countStatementName = statementName.replaceAll("SELECT", "COUNT");
        Long totalCount = (Long) queryForObject(countStatementName, queryParam);
        if (totalCount == 0) {
            return new DataList();
        }

        DataList dataList = new DataList();
        int pageSize = queryParam.getPageSize();
        int totalPage = calTotalPage(totalCount, pageSize);
        int pageNo = queryParam.getPageNo();
        pageNo = Math.max(1, pageNo); // pageNo must >=1;
        pageNo = Math.min(pageNo, totalPage); // pageNo must <=totalPage;
        dataList.setPageNo(pageNo);
        dataList.setTotalPage(totalPage);
        dataList.setTotalCount(totalCount);
        Map<String, Integer> parameter = new HashMap<String, Integer>();
        parameter.put("pageSize", pageSize);
        parameter.put("startRow", (pageNo - 1) * pageSize);
        parameter.put("endRow",  pageSize);
        parameter.putAll(queryParam);
        List list = super.queryForList(statementName, parameter);
        dataList.setData(list);
        return dataList;
    }

    public int calTotalPage(long rowNum, int pageSize) {
        if (rowNum % pageSize == 0) {
            return (int) (rowNum / pageSize);
        } else {
            return (int) ((rowNum / pageSize) + 1);
        }

    }

}
